﻿using System;
using System.Device.Location;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Microsoft.WindowsAzure.MobileServices;
using SkiTracker.Model;
using Windows.Devices.Geolocation;

namespace SkiTracker.ViewModel
{
    public class SendMessageViewModel : ViewModelBase
    {
        private readonly IMobileServiceTable<Message> _messageTable = App.MobileService.GetTable<Message>();

        public SendMessageViewModel()
        {
            SendCommand = new RelayCommand(Send);
            SendFixCommand = new RelayCommand<string>(Send);
        }


        private void Send()
        {
            Send(Message);
        }

        private async void Send(string messageText)
        {
            Message = string.Empty;

            var geolocator = new Geolocator
                {
                    DesiredAccuracyInMeters = 30,
                };

            var currentLocation = await geolocator.GetGeopositionAsync(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15));

            var message = new Message
                {
                    Text = messageText,
                    DeviceId = App.CurrentApp.CurrentDevice.Id,
                    //SenderName = App.CurrentApp.CurrentDevice.Name,
                    GroupName = App.CurrentApp.CurrentDevice.GroupName,
                    Coordinate = new GeoCoordinate(currentLocation.Coordinate.Latitude, currentLocation.Coordinate.Longitude),
                };

          await _messageTable.InsertAsync(message);
        }

        private string _message;
        public string Message
        {
            get { return _message; }
            set
            {
                _message = value;
                RaisePropertyChanged(() => Message);
                SendCommand.RaiseCanExecuteChanged();
            }
        }

        public RelayCommand SendCommand { get; private set; }
        public RelayCommand<string> SendFixCommand { get; private set; }
    }
}
